Strings¶

In [44]:
'this is a string'
Out[44]:
'this is a string'

🎨 len¶

In [45]:
len('word and word')
Out[45]:
13

You can use len to get the length of a string.

🖌 Building Strings¶

In [46]:
'fire' + 'place'
Out[46]:
'fireplace'
In [49]:
'yo' * 2
Out[49]:
'yoyo'
In [50]:
'nan ' * 16 + 'batman!'
Out[50]:
'nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan batman!'
batman!

🖌 +=¶

In [51]:
message = 'Hello'
message = message + ' world!'
message
Out[51]:
'Hello world!'
In [52]:
message = 'Hello'
message += ' world!'
message
Out[52]:
'Hello world!'

🖌 String Iteration¶

In [54]:
for letter in 'this is a string':
    print(letter)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g

🎨 Character classes¶

In [55]:
'a'.isalpha(), '8'.isalpha()
Out[55]:
(True, False)
In [56]:
'abcdefg'.isalpha(), 'abc1234'.isalpha(), 'abc!'.isalpha()
Out[56]:
(True, False, False)
In [57]:
'a'.isdigit(), '8'.isdigit()
Out[57]:
(False, True)
In [58]:
'12345'.isdigit(), '12345pi'.isdigit(), '123.456'.isdigit()
Out[58]:
(True, False, False)
In [59]:
'a'.isalnum(), '8'.isalnum()
Out[59]:
(True, True)
In [60]:
'12345'.isalnum(), '12345pi'.isalnum(), '123.456'.isalnum()
Out[60]:
(True, True, False)
In [61]:
'a'.isspace(), '8'.isspace(), ' '.isspace()
Out[61]:
(False, False, True)
In [62]:
'A'.islower(), 'A'.isupper()
Out[62]:
(False, True)
In [63]:
'a'.islower(), 'a'.isupper(), '9'.islower(), '9'.isupper()
Out[63]:
(True, False, False, False)
In [64]:
'a'.upper(), 'a'.lower()
Out[64]:
('A', 'a')
In [65]:
'A'.upper(), 'A'.lower()
Out[65]:
('A', 'a')
In [66]:
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_+=[]{}"\'|:;,./?<> \t\n'
In [67]:
# isalpha
alphas = ''
for character in characters:
    if character.isalpha():
        alphas += character
print(alphas)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
In [68]:
# isdigit
digits = ''
for character in characters:
    if character.isdigit():
        digits += character
print(digits)
0123456789
In [69]:
# isalnum
alphanumeric = ''
for character in characters:
    if character.isalnum():
        alphanumeric += character
print(alphanumeric)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
In [70]:
# isspace
spaces = ''
for character in characters:
    if character.isspace():
        spaces += character
print(spaces)
 	

😶
In [73]:
# isspace
spaces = []
for character in characters:
    if character.isspace():
        spaces.append(character)
print(spaces)

for space in spaces:
    print(f'>>{space}<<')
    
[' ', '\t', '\n']
>> <<
>>	<<
>>
<<
hello
world!
In [76]:
# other stuff
symbols = ''
for character in characters:
    if not character.isspace() and not character.isalnum():
        symbols += character
print(symbols)
`~!@#$%^&*()-_+=[]{}"'|:;,./?<>
In [79]:
# upper and lower
uppers = ''
lowers = ''
for character in characters:
    if character.isupper():
        uppers += character
    elif character.islower():
        lowers += character
print(uppers)
print(lowers)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

👩🏻‍🎨 No Spaces¶

Write a function that replaces all space characters with dashes.

In [80]:
def no_spaces(text: str) -> str:
    """Replace all space characters with dashes"""
    new_string = ''
    for letter in text:
        if letter.isspace():
            letter = '-'
        new_string += letter
    return new_string


    new_string = ''
    for c in text:
        if c.isspace():
            new_string += '-'
        else:
            new_string += c
    return new_string
In [ ]:
def no_spaces(text):
    result = ''
    for c in text:
        if c.isspace():
            c = '-'
        result += c
    return result
In [81]:
print(no_spaces('BYU is the place to be.'))
BYU-is-the-place-to-be.
In [83]:
message = """This is a long,
multiline "string".
It has multiple lines.
That is what "multiline" means. :)"""

print(message)
print()
print(no_spaces(message))
This is a long,
multiline "string".
It has multiple lines.
That is what "multiline" means. :)

This-is-a-long,-multiline-"string".-It-has-multiple-lines.-That-is-what-"multiline"-means.-:)
In [84]:
print(no_spaces('Goodbye spaces \t tabs \n and newlines'))
Goodbye-spaces---tabs---and-newlines

👨🏾‍🎨 Numbers?¶

Write a function that replaces every digit in a string with ?

In [85]:
def no_numbers(text: str) -> str:
    """Replace every digit with ?"""
    new_string = ''
    for character in text:
        if character.isdigit():
            character = '?'
        new_string += character
    return new_string
In [ ]:
def no_numbers(text):
    result = ''
    for char in text:
        if char.isdigit():
            result = result + '?'
        else:
            result = result + char
    return result
In [86]:
no_numbers('There were 7 people.')
Out[86]:
'There were ? people.'
In [87]:
no_numbers('15 out of 25 have more than 17.3% contamination.')
Out[87]:
'?? out of ?? have more than ??.?% contamination.'
In [88]:
no_numbers('2 + 2 = 5, for large values of 2.')
Out[88]:
'? + ? = ?, for large values of ?.'

🧑🏻‍🎨 Sum of Digits¶

Add up all the digits found in a string.

In [89]:
def find_digits(text: str) -> str:
    """Return a string of just the digits"""
    digits = ''
    for char in text:
        if char.isdigit():
            digits += char
    return digits


def turn_to_ints(digits: str) -> list[int]:
    """Turn each digit in the string to an int. Return a list of int."""
    numbers = []
    for digit in digits:
        numbers.append(int(digit))
    return numbers
#     return [int(n) for n in digits]
    

def add_digits(text: str) -> int:
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    digits = find_digits(text)
    numeric_digits = turn_to_ints(digits)
    total = sum(numeric_digits)
    return total
In [ ]:
def add_digits(text):
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    total = 0
    for c in text:
        if c.isdigit():
            total += int(c)
    return total
In [90]:
add_digits('123foo')
Out[90]:
6
In [91]:
add_digits('10 students ate 6 oranges and 42 students ate 7 pears.')
Out[91]:
20

🧑🏽‍🎨 Organized¶

Write a program that "organizes" user input.

"Organized" text means that all the characters are reordered to this sequence:

  • lowercase letters
  • uppercase letters
  • digits
  • everything else
  • whitespace is removed

organize.py¶

Text: Hello, what is your name?
ellowhatisyournameH,?
Text: BYU is my favorite school!
ismyfavoriteschoolBYU!
Text: 3.14159 is a loose approx. for PI.
isalooseapproxforPI314159...
Text:

Key Ideas¶

  • String iteration
  • 'foo' + 'bar', 'BYU! ' * 5
  • .isalpha(), .isdigit(), .isalnum(), .isspace(), .isupper(), .islower()
  • .upper(), .lower()
  • +=